package com.publish.file.controller;

import java.util.ArrayList;

import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.publish.file.repository.user.LoginResponse;
import com.publish.file.service.auth.AuthService;
import com.publish.file.service.auth.RoleConstant;
import com.publish.file.service.jwt.JwtService;

@CrossOrigin
@Validated
@RestController
@RequestMapping("/auth")
public class AuthRestController {
	@Autowired
	JwtService jwtServiceImpl;
	@Autowired
	AuthService authServiceImpl;

	@RequestMapping("/login")
	public Result<LoginResponse> login(
			@Validated @RequestParam("name") @Length(min = 3, max = 36, message = "用户名3~36") String userName,
			@Validated @RequestParam("password") @Length(min = 6, max = 36, message = "密码长度为6~36") String password) {
		boolean result = authServiceImpl.vertify(userName, password);
		if (!result) {
			return Result.fail(Result.CODE_NOPERMIT, Result.CODE_NOPERMIT_STRING);
		}
		try {
			String token = jwtServiceImpl.generateToken(userName);
			ArrayList<String> roles = new ArrayList<String>();
			roles.add(RoleConstant.ROLE_DEV);
			return Result.success(new LoginResponse(token, userName, roles));
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(Result.CODE_GEN_TOKEN, Result.CODE_GEN_TOKEN_STRING);
		}
	}
}
